package top.kaoshanji.q2ch16a.api;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriComponentsBuilder;
import top.kaoshanji.q2ch16a.exception.NotFound404Exception;
import top.kaoshanji.q2ch16a.model.Spittle;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;

/**
 * 代码清单-q2ch16a-439页a：为控制器默认设置消息转换，使用@RestController注解
 * @author kaoshanji
 * ^_^
 * create time 2025/4/26 10:52
 */
@RestController
@RequestMapping("/spittles1")
public class SpittleApiController1 {

    @RequestMapping(value = "/spittleDetail/{spittleId}", method = RequestMethod.GET)
    public Spittle spittleDetail(@PathVariable("spittleId") long spittleId) {
        Spittle spittle = new Spittle();

        spittle.setId(spittleId);
        spittle.setMessage("我是靓仔");

        return spittle;
    }

    @RequestMapping(value = "/saveSpittle", method = RequestMethod.POST)
    public Map<String, String> saveSpittle(@RequestBody Spittle spittle) {
        System.out.println("来自客户端的数据：" + spittle.getMessage());

        Map<String, String> map = new HashMap<>();
        map.put("userName", "我是靓仔");

        return map;
    }

    /**
     * 代码清单-q2ch16a-444页a：这是一个处理错误的API接口
     * @param spittleId
     * @return
     */
    @RequestMapping(value = "/spittleException/{spittleId}", method = RequestMethod.GET)
    public Spittle spittleException(@PathVariable("spittleId") long spittleId) {
        Spittle spittle = null;

        System.out.println("这是一个处理错误的API接口....");

        if (spittle == null) {
            throw new NotFound404Exception(spittleId);
        }

        return spittle;
    }

    @ExceptionHandler(NotFound404Exception.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public Error spittleNotFound(NotFound404Exception exception) {
        long spittleId = exception.getSpittleId();
        return new Error(4, "Spittle [" + spittleId + "] not found");
    }

    /**
     * 代码清单-q2ch16a-446页a：使用ResponseEntity在响应中设置头部信息
     * @param spittle
     * @param ucb
     * @return
     */
    @RequestMapping(value = "/saveSpittleEntity", method = RequestMethod.POST)
    public ResponseEntity<Spittle> saveSpittleEntity(@RequestBody Spittle spittle, UriComponentsBuilder ucb) {
        spittle.setId(10L);

        HttpHeaders httpHeaders = new HttpHeaders();
        URI locationUri = ucb.path("/spittles1/spittleDetail/")
                .path(String.valueOf(spittle.getId()))
                .build().toUri();
        httpHeaders.setLocation(locationUri);

        ResponseEntity<Spittle> responseEntity = new ResponseEntity<>(spittle, httpHeaders, HttpStatus.CREATED);

        return responseEntity;
    }

}
